#include <stdio.h>
#include <stdbool.h>

//初始化函数
void InitBoard(char (*Board)[3])
{
    for(int i = 0; i < 3; i++)
    {
        for(int j = 0; j < 3; j++)
        {
            Board[i][j] = ' ';
        }
    }
}

//打印棋盘
void PrintBoard(char(*Board)[3])
{
    for(int i = 0; i < 3; i++)
    {
        for(int j = 0 ; j < 3; j++)
        {
            printf(" %c ",Board[i][j]);
            if(j < 2)
                printf("|");
        }
        printf("\n");
        if(i < 2)
            printf("---|---|---\n");
    }
}

//下棋
 bool MakeMove(char (*Board)[3], int row, int column, char player)
{
    if(row < 0 || row >= 3 || column < 0 || column >= 3)
    {
        printf("下的位置是非法位置，请重新输入！");
        return false;
    }
    if(Board[row][column] != ' ')
    {
        printf("当前位置已经有棋子了，请重新输入！\n");
        return false;
    }
    Board[row][column] = player;
    return true;
}

//判断是否胜利
bool CheckIsWin(char(*Board)[3],char player)
{
    for(int i = 0; i < 3; i++)
    {
        int count = 0; 
        while(Board[i][count] == player && count < 3)
        {
            count++;
        }
        if(count == 3)
        {
            return true;
        }
        
    }
    for(int j = 0; j < 3; j++)
    {
        int count = 0;
        while(Board[count][j] == player && count < 3)
        {
            count++;
        }
        if(count == 3)
        {
            return true;
        }
    }
    if(Board[0][0] == player && Board[1][1] == player && Board[2][2] == player)
    return true;
    if(Board[0][2] == player && Board[1][1] == player && Board[2][0] == player)
    return true;

    return false;
}

//判断是否是平局
bool CheckIsDraw(char(*Board)[3])
{
    for(int i = 0; i < 3; i++)
    {
        for(int j = 0; j < 3;j++)
        {
            if(Board[i][j] == ' ')
            return false;
        }
    }
    return true;//平局
}
int main()
{
    char Board[3][3] = {0};
    //调用函数
    InitBoard(Board);
    //PrintBoard(Board);

    char player = 'X';
    while(1)
    {
        PrintBoard(Board);
        int row = 0; 
        int column = 0;
        printf("请玩家|%c|下棋：",player);
        //从终端读取输入
        scanf("%d %d",&row,&column);
        if(MakeMove(Board,row - 1, column - 1,player) == false)
        {
            continue;
        }
        if(CheckIsWin(Board,player) == true)
        {
            PrintBoard(Board);
            printf("恭喜|%c|玩家获胜！\n",player);
            break;
        }
        if(CheckIsDraw(Board) == true)
        {
            PrintBoard(Board);
            printf("平局！\n");
            break;
        }
        player = (player == 'X') ? 'O' : 'X';   
    }
    return 0;
}